﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.Utils;
using System.Diagnostics;
using JN.Utility;
using LogManager;
using Power.Common;

namespace Power
{
    public partial class MainForm : DevExpress.XtraEditors.XtraForm
    {
        #region property
        Manager.SystemStatus sysStatus = Manager.SystemStatus.Instance;
        #endregion
        private Dictionary<string, DevExpress.XtraTab.XtraTabPage> tablePagesList = new Dictionary<string, DevExpress.XtraTab.XtraTabPage>();
        private static readonly object _lockObj = new object();
        private static MainForm _instance = null;
        public static MainForm Instance
        {
            get
            {
                lock (_lockObj)
                {
                    if (_instance == null)
                    {
                        _instance = new MainForm();
                    }
                    return _instance;
                }
            }
        }
        public MainForm()
        {
            InitializeComponent();
        }

        private void sys_timer_Tick(object sender, EventArgs e)
        {
            barBTime.Caption = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            //load 
            ShowWelcomeForm();
            GetStationIonfo();
            CheckUserMenu();
            Power.Manager.Manager.Initalize();
            MeterControl.MeterPH600.UpdateStatus +=new MeterControl.MeterPH600.UpdateStatusHandler(MeterPH600_UpdateStatus);
            this.Activate();
        }
        private void ShowWelcomeForm()
        {
            WinUI.WelcomeForm welcome = new WinUI.WelcomeForm();
            AddFormInPanel(welcome);
        }
        private void GetStationIonfo()
        {
            try
            {
                //db conn
                string str = Config.SystemConfig.Instance.GetConnString(); ;
                int left = str.IndexOf("=");
                int leng = str.IndexOf(';');
                string dbIP = str.Substring(left + 1, leng - left - 1);
                str = str.Substring(leng + 1, str.Length - leng - 1);

                left = str.IndexOf("=");
                leng = str.IndexOf(';');
                string dbName = str.Substring(left + 1, leng - left - 1);
                //ip ,schema
                barDatabaseIp.Caption = "服务器( "+dbIP+" ) ";
                barDatabaseName.Caption =" {"+ dbName+"} ";                

                BLL.Station_infoBLL stationBLL = new BLL.Station_infoBLL();
                string id = Manager.SystemStatus.Instance.Station_id != null ? Manager.SystemStatus.Instance.Station_id : "";
                Model.Station_info mStation = stationBLL.GetModel(id);
                if (mStation != null)
                {
                    barStation.Caption = mStation.station_name;
                    this.Text = mStation.station_name;
                }
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);   
            }
        }
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //close
            if (XtraMessageBox.Show("系统将关闭，确认退出系统？", "提示",MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                Manager.Manager.ExitSystem();
                DataBaseLogger.Write(DbLogType.UserLogOff, "用户:" + Manager.SystemStatus.Instance.Login_user+ "登出系统.", Manager.SystemStatus.Instance.Station_id);
                e.Cancel = false;
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void barLargeButtonItem4_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.Close();
        }

        private void barLargeButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            About.AboutBox1 about = new About.AboutBox1();
            about.ShowDialog();
        }
        public void AddFormInPanel(XtraForm from)
        {
            try
            {
                DevExpress.XtraTab.XtraTabPage tabPage = new DevExpress.XtraTab.XtraTabPage();
                from.TopLevel = false;
                from.Dock = DockStyle.Fill;                
                from.FormBorderStyle = FormBorderStyle.None;
                tabPage.Text = from.Text;
                tabPage.Name = from.Name;
                from.Show();
                tabPage.Controls.Add(from);
                tabPages.TabPages.Add(tabPage);
                tabPages.SelectedTabPage = tabPage;
                if (!tablePagesList.ContainsKey(from.Name))
                {
                    tablePagesList.Add(from.Name, tabPage);
                }
                tabPages.ShowTabHeader = DefaultBoolean.False;
            }
            catch (Exception ex)
            {
                Common.Notify.NotifyMessage.Show(ex);
            }
        }

        private void barLargeButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {            
            ShowWelcomeForm();
        }

        private void barLargeButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            LockForm();
        }
        private void LockForm()
        {
            WinUI.LockUser logon = new WinUI.LockUser();
            logon.UserId = Manager.SystemStatus.Instance.Login_user;
            logon.StationId = Manager.SystemStatus.Instance.Station_id;
            logon.ShowDialog();            
            if (logon.DialogResult != System.Windows.Forms.DialogResult.OK)
            {
                splitContainerControl1.Enabled = false;
            }
            else
            {
                splitContainerControl1.Enabled = true;
            }            
        }
        private void navBarItem3_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            LockForm();
        }

        private void navBarItem2_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            //System.Windows.Forms.PrintDialog PrintDialog1 = new PrintDialog();
            //System.Windows.Forms.PrintPreviewDialog dial = new PrintPreviewDialog();
            //dial.ShowDialog();
            //PrintDialog1.PageSetupDialog();
        }

        private void navBarItem1_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            WinUI.DFilesMange dfile = new WinUI.DFilesMange();
            AddFormInPanel(dfile);
        }

        private void navBarItem4_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            UserInfo.UserManager users = new UserInfo.UserManager();
            AddFormInPanel(users);
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void navBarChangePwd_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            UserInfo.ChangePassword changePwd = new UserInfo.ChangePassword();
            changePwd.User_id = Manager.SystemStatus.Instance.Login_user;
            changePwd.ShowDialog();
        }
        /// <summary>
        /// 用户管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void navBarUserMgt_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            UserInfo.UserInfo users = new UserInfo.UserInfo();
            AddFormInPanel(users);
        }
        /// <summary>
        /// 站点管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void navBarStation_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            MeterInfo.StationInfo station = new MeterInfo.StationInfo();
            AddFormInPanel(station);
        }
        /// <summary>
        /// 电器柜管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void nvvBarChest_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            MeterInfo.ChestInfo chest = new MeterInfo.ChestInfo();
            AddFormInPanel(chest);
        }
        /// <summary>
        /// 电表管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void navBarDevice_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            MeterInfo.MeterInfo meter = new MeterInfo.MeterInfo();
            AddFormInPanel(meter);
        }
        /// <summary>
        /// 串口服务器测试节点测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void navBarCommTest_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            ComManager.NodeList nodes = new ComManager.NodeList();
            nodes.ShowDialog();
        }
        /// <summary>
        /// COM 口测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void navBarComPortTest_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            ComManager.ComList comm = new ComManager.ComList();
            comm.ShowDialog();
        }
        /// <summary>
        /// 日志查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void navBarLog_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            LogManager.WinUI.QueryLog qLog = new LogManager.WinUI.QueryLog();
            AddFormInPanel(qLog);
        }
        /// <summary>
        /// 警告查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void navBarAlarm_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            LogManager.WinUI.QueryAlarm qAlarm = new LogManager.WinUI.QueryAlarm();
            AddFormInPanel(qAlarm);
        }
        /// <summary>
        /// 通信状态图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void navBarCommLayout_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            Layouts.CommStatus stat = new Layouts.CommStatus();
            AddFormInPanel(stat);
        }
        /// <summary>
        /// 报表link web
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void navBarReport_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            StartUrl();
        }
        /// <summary>
        /// 设置数据库连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barDatabaseIp_ItemDoubleClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Config.SetDataBase setDb = new Config.SetDataBase();
            setDb.ShowDialog();
        }
        /// <summary>
        /// 手动测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void navBarMeterManual_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            //get manual
            string mType = System.Configuration.ConfigurationManager.AppSettings.Get("MeterType");
            if (mType == "PH630")
            {
                MeterControl.MeterManual_PH manual = new MeterControl.MeterManual_PH();
                AddFormInPanel(manual);
            }
            else
            {
                MeterControl.MeterManual_EQ manual = new MeterControl.MeterManual_EQ();
                AddFormInPanel(manual);
            }

            
        }
        /// <summary>
        /// 系统设定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void navBarSysSet_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            Config.SystemSet set = new Config.SystemSet();
            AddFormInPanel(set);
        }
        #region sys func
        /// <summary>
        /// 按照用户的角色
        /// </summary>
        private void CheckUserMenu()
        {
            try
            {
                switch (Manager.SystemStatus.Instance.User_Role)
                {
                    case "0000":
                        #region 超级管理员
                        //基本操作
                        navBarChangePwd.Enabled = true;
                        navBarUserMgt.Enabled = true;
                        
                        //系统资料
                        navBarSysSet.Enabled = true;
                        navBarStation.Enabled = true;
                        nvvBarChest.Enabled = true;
                        navBarDevice.Enabled = true;

                        //硬件通信
                        navBarCommTest.Enabled = true;
                        navBarComPortTest.Enabled = true;
                        navBarMeterManual.Enabled = true;

                        //图形检测
                        navBarCommLayout.Enabled = true;
                        navBarItem10.Enabled =true;

                        //查询功能
                        navBarLog.Enabled = true;
                        navBarItem16.Enabled = true;
                        navBarReport.Enabled = true;

                        //实时告警
                        navBarAlarm.Enabled = true;
                        #endregion

                        break;
                    case "0001":
                        #region 管理员
                        //基本操作
                        navBarChangePwd.Enabled = true;
                        navBarUserMgt.Enabled = true;

                        //系统资料
                        navBarSysSet.Enabled = true;
                        navBarStation.Enabled = true;
                        nvvBarChest.Enabled = true;
                        navBarDevice.Enabled = true;

                        //硬件通信
                        navBarCommTest.Enabled = false;
                        navBarComPortTest.Enabled = false;
                        navBarMeterManual.Enabled = false;

                        //图形检测
                        navBarCommLayout.Enabled = true;
                        navBarItem10.Enabled = true;

                        //查询功能
                        navBarLog.Enabled = true;
                        navBarItem16.Enabled = true;
                        navBarReport.Enabled = true;

                        //实时告警
                        navBarAlarm.Enabled = true;

                        #endregion

                        break;
                    case "0002":
                        #region 工程师
                        //基本操作
                        navBarChangePwd.Enabled = true;
                        navBarUserMgt.Enabled = false;

                        //系统资料
                        navBarSysSet.Enabled = false;
                        navBarStation.Enabled = false;
                        nvvBarChest.Enabled = false;
                        navBarDevice.Enabled = false;

                        //硬件通信
                        navBarCommTest.Enabled = false;
                        navBarComPortTest.Enabled = false;
                        navBarMeterManual.Enabled = false;

                        //图形检测
                        navBarCommLayout.Enabled = true;
                        navBarItem10.Enabled = true;

                        //查询功能
                        navBarLog.Enabled = true;
                        navBarItem16.Enabled = true;
                        navBarReport.Enabled = true;

                        //实时告警
                        navBarAlarm.Enabled = true;
                        #endregion

                        break;
                    case"0003":
                        #region 操作员
                        //基本操作
                        navBarChangePwd.Enabled = true;
                        navBarUserMgt.Enabled = false;

                        //系统资料
                        navBarSysSet.Enabled = false;
                        navBarStation.Enabled = false;
                        nvvBarChest.Enabled = false;
                        navBarDevice.Enabled = false;

                        //硬件通信
                        navBarCommTest.Enabled = false;
                        navBarComPortTest.Enabled = false;
                        navBarMeterManual.Enabled = false;

                        //图形检测
                        navBarCommLayout.Enabled = true;
                        navBarItem10.Enabled = true;

                        //查询功能
                        navBarLog.Enabled = false;
                        navBarItem16.Enabled = true;
                        navBarReport.Enabled = true;

                        //实时告警
                        navBarAlarm.Enabled = true;
                        #endregion

                        break;
                }
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }
        private void MeterPH600_UpdateStatus(MsgType msgType, object msg)
        {
            try
            {
                switch (msgType)
                {
                    case MsgType.ShowError:
                        Common.Notify.NotifyMessage.ShowNoDialog("系统错误", msg.ToString());
                        break;
                    case MsgType.ShowEvent:
                        ShowEvent(msg);
                        break;
                }
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }
        private void ShowEvent(object msg)
        {
            Application.DoEvents();
            Common.Notify.NotifyMessage.ShowNoDialog("系统事件", msg.ToString());
            Application.DoEvents();
        }
        private void StartUrl()
        {
            try
            {
                BLL.Sys_reportBLL rptBLL = new BLL.Sys_reportBLL();
                string url = string.Empty;
                string sql = " station_id ='"+sysStatus.Station_id+"' ";
                DataTable dt = rptBLL.GetList(sql).Tables[0];
                if (dt.Rows.Count>0)
                {
                    //start url
                    url = dt.Rows[0]["url"].ToString();
                    if (!System.Uri.IsWellFormedUriString(url, UriKind.Absolute))
                    {
                        Common.Notify.NotifyMessage.Show("报表链接地址格式不正确，请联系管理员!", "错误");
                    }
                    else
                    {                        
                        Process ps = new Process();                        
                        ps.StartInfo.FileName = "iexplore.exe";
                        ps.StartInfo.Arguments = url;
                        ps.Start();
                    }
                }
                else
                {
                    Common.Notify.NotifyMessage.Show("启动报表数据错误，未找到链接。请联系管理员!", "错误");
                }
            }
            catch (Exception ex)
            {
                Common.Notify.NotifyMessage.Show(ex);
            }
        }
        #endregion
    }
}